﻿//https://leetcode.cn/problems/linked-list-cycle-ii/?envType=study-plan-v2&envId=top-100-liked

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* detectCycle(ListNode* head)
    {
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast != nullptr)
        {
            slow = slow->next;
            if (fast->next == nullptr)
            {
                return nullptr;
            }
            fast = fast->next->next;
            if (fast == slow)
            {
                //一个指针从起始点开始走，一个指针从相交点开始走，相遇的位置为入口点
                ListNode* temp = head;
                while (temp != slow)
                {
                    temp = temp->next;
                    slow = slow->next;
                }

                return temp;
            }
        }

        return nullptr;

    }
};